﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using Zocono.Infrastructure.Common;

namespace Zocono.WCS.Admin.Common
{
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogUtil _LogUtil;

        public ExceptionFilter(ILogUtil logUtil)
        {
            _LogUtil = logUtil;
        }

        public void OnException(ExceptionContext context)
        {
            Exception ex = context.Exception;
            var et = ex.GetType();
            _LogUtil.Error($"发生未知的异常:{ex}");

            string json = JsonConvert.SerializeObject(new
            {
                isSucceed = false,
                result = false,
                message = ex.Message
            });
            context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
            context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
            context.HttpContext.Response.WriteAsync(json);
            context.ExceptionHandled = true;

        }
    }
}
